{"componentChunkName":"component---src-templates-post-jsx","path":"/[Java지식]얕은복사&깊은복사/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"92c9220c-c4b0-59a2-a626-5a22f979bf39","excerpt":"이전에 BOJ_연구소를 풀다가, 배열 두 개를 사용하여 값을 변경하고 초기화하는 작업을 하던 중 의도와 다르게 두 배열의 값이 동기화된 것처럼 같이 변경되는 문제를 확인했다.  그래서 \"얕은 복사와 깊은 복사\"에 대해 정리하려 한다. 내가 맞닥뜨린 문제이므로 정리하고 이해하고 넘어가고자 한다. 📍 자바의 객체 복사 자바에서는 객체를 복사하는 유형으로 얕은…","html":"<p>이전에 <a href=\"https://subbblog.netlify.app/BOJ-14502/\">BOJ_연구소</a>를 풀다가, 배열 두 개를 사용하여 값을 변경하고 초기화하는 작업을 하던 중 의도와 다르게 두 배열의 값이 동기화된 것처럼 같이 변경되는 문제를 확인했다. </p>\n<p>그래서 <strong>\"얕은 복사와 깊은 복사\"</strong>에 대해 정리하려 한다. 내가 맞닥뜨린 문제이므로 정리하고 이해하고 넘어가고자 한다.</p>\n<h2>📍 자바의 객체 복사</h2>\n<p>자바에서는 객체를 복사하는 유형으로 <strong>얕은 복사</strong>와 <strong>깊은 복사</strong>가 있다.</p>\n<h3>📝 얕은 복사 (Shallow Copy)</h3>\n<p>단순히 객체의 주소 값만을 복사하는 방식이다.</p>\n<ul>\n<li>\n<p><strong>여러 객체가 같은 주소를 참조</strong>해 하나의 값을 변경하면 다른 대상의 값 또한 바뀐다.</p>\n<ul>\n<li>즉, 객체는 여러 개이지만,그 객체 각각이 가리키는 값은 동일한 주소 값이다. 그렇기에 대개 복사가 아닌 <strong>같이 사용한다-</strong>정도의 개념이 알맞다.</li>\n</ul>\n</li>\n<li>메모리 측면에서는 한 객체로 가능하다면 이 방식을 사용하는 것이 효율적이다.</li>\n</ul>\n<h3>📝 깊은 복사 (Deep Copy)</h3>\n<p>객체의 실제값을 새로운 객체로 복사하는 방식이다.</p>\n<ul>\n<li>실제로 대상이 여러 개가 생기므로, <strong>각 값이 모두 개별적</strong>이다.</li>\n<li>하지만 쓸데없이 여러 객체를 생성한다면 메모리 측면에서는 효율적이지 못하다.</li>\n</ul>\n<blockquote>\n<p>우선 내가 원한 로직은 <code class=\"language-text\">copyMap</code> 의 값을 변경하고 이를 다시 되돌리기 위해 <code class=\"language-text\">map</code> 을 이용하려 했다. 얕은 복사와 깊은 복사를 내가 풀었던 코드에 대입하여 표현하면 아래와 같다.</p>\n</blockquote>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Lab {\n\tint[][] map;\n\tint[][] copyMap;\n\n\tpublic Lab (int N, int M) {\n\t\tmap = new int[N][M];\n\t\tcopyMap = new int[N][M];\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">Lab</code> 클래스를 생성하고, 두 배열(<code class=\"language-text\">map</code> , <code class=\"language-text\">copyMap</code>)을 생성한다. </li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Main {\n\tpublic static void main(String[] args) {\n\t\t// N, M이 입력되었다고 가정\n\t\tint N, M;\n\n\t\t// 생성자로 map, copyMap을 생성\n\t\tLab lab = new Lab(N, M);\n\n\t\t// lab.map에 먼저 값을 대입하고, 이를 copyMap에 동일하게 대입\n\t\tfor (int i = 0; i &lt; N; i++) {\n\t\t\tlab.map[i] = Arrays.stream(br.readLine().split(&quot; &quot;)).mapToInt(Integer::parseInt).toArray();\n\t\t\t// 얕은 복사\n\t\t\tlab.copyMap[i] = lab.map[i];\n\t\t}\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>이후 배열을 초기화하는데, <code class=\"language-text\">=</code> 연산자를 사용해서 <code class=\"language-text\">copyMap</code> 을 초기화했다.</li>\n</ul>\n<p>여기서 <code class=\"language-text\">=</code> 연산자는 <strong>주소를 이어준다</strong>는 의미를 가진다. 즉, <code class=\"language-text\">lab.copyMap[i]</code> 와 <code class=\"language-text\">lab.map[i]</code> 의 주소를 이어, 깊은 복사가 아닌 얕은 복사가 수행되고 두 배열의 값이 함께 수정되어버린다.</p>\n<blockquote>\n<p>이를 깊은 복사로 변경한다. 깊은 복사는 여러 가지 방법이 있다. 나는 우선 간단한 for문으로 깊은 복사를 수행했다.</p>\n</blockquote>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Main {\n\tpublic static void main(String[] args) {\n\t\t// N, M이 입력되었다고 가정\n\t\tint N, M;\n\n\t\t// 생성자로 map, copyMap을 생성\n\t\tLab lab = new Lab(N, M);\n\n\t\t// lab.map에 먼저 값을 대입하고, 이를 copyMap에 동일하게 대입\n\t\tfor (int i = 0; i &lt; N; i++) {\n\t\t\tlab.map[i] = Arrays.stream(br.readLine().split(&quot; &quot;)).mapToInt(Integer::parseInt).toArray();\n\t\t\t// 깊은 복사\n\t\t\tfor (int j = 0; j &lt; M; j++) {\n\t\t\t\tlab.copyMap[i][j] = lab.map[i][j];\n\t\t\t}\n\t\t}\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>간단한 반복문으로 배열의 원소를 하나하나 대입하였다.</li>\n</ul>\n<h3>📝 깊은 복사 메소드</h3>\n<p>아래는 모두 1차원 배열에 대해 가능한 깊은 복사 메소드이다. 2차원 배열에 대해서는 이와 같이 불가능한데, 다음과 같은 이유에서이다.</p>\n<ul>\n<li>2차원 배열의 구조(<code class=\"language-text\">map[x][y]</code>)에서 배열을 복사하는 메소드를 사용하면, <code class=\"language-text\">y</code> 좌표를 가리키는 주소값만 있는 <code class=\"language-text\">map[x]</code> 부분만 깊은 복사가 되고, 값이 있는 <code class=\"language-text\">map[x][y]</code> 는 깊은 복사가 수행되지 않는다.</li>\n<li>따라서, 이중 for문을 활용하거나, 가장 마지막에 있는 <code class=\"language-text\">System.arraycopy</code> 를 활용해야 한다.</li>\n</ul>\n<p><strong><code class=\"language-text\">Object.clone()</code></strong></p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Main {\n\tpublic static void main(String[] args) {\n\t\tint[] map = { 0, 1, 2, 3 };\n\t\tint[] copyMap = map.clone(); \n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>가장 보편적인 깊은 복사 방법이다.</li>\n</ul>\n<p><strong><code class=\"language-text\">Arrays.copyOf()</code></strong></p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">import java.util.Arrays;\n\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tint[] map = { 0, 1, 2, 3 };\n\t\tint[] copyMap = Arrays.copyOf(map, map.length);\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">Arrays</code> 클래스는 배열을 다루는 메소드를 가진 클래스이다. 이 클래스의 <code class=\"language-text\">copyOf()</code> 를 사용하면 배열의 시작점부터 원하는 <code class=\"language-text\">length</code> 까지 깊은 복사를 수행할 수 있다.</li>\n</ul>\n<p><strong><code class=\"language-text\">Arrays.copyOfRange()</code></strong></p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">import java.util.Arrays;\n\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tint[] map = { 0, 1, 2, 3 };\n\t\tint[] copyMap = Arrays.copyOfRange(map, 1, 3);\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">Arrays.copyOf()</code> 는 배열의 시작점부터 원하는 <code class=\"language-text\">length</code> 까지 복사하는 메소드였다면, <code class=\"language-text\">copyOfRange()</code> 는 복사할 시작점 또한 지정 가능하다. (0행부터 시작)</li>\n</ul>\n<p><strong><code class=\"language-text\">System.arraycopy()</code></strong></p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Main {\n\tpublic static void main(String[] args) {\n\t\tint[] map = { 0, 1, 2, 3 };\n\t\tint[] copyMap = new int[map.length];\n\t\tSystem.arraycopy(map, 0, copyMap, 0, map.length);\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>1차원 배열에 대해 지정한 배열을 대상 배열의 지정한 위치에 <code class=\"language-text\">length</code> 만큼 복사한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">public class Main {\n\tpublic static void main(String[] args) {\n\t\t// N, M이 입력되었다고 가정\n\t\tint N, M;\n\n\t\t// 생성자로 map, copyMap을 생성\n\t\tLab lab = new Lab(N, M);\n\n\t\t// lab.map에 먼저 값을 대입하고, 이를 copyMap에 동일하게 대입\n\t\tfor (int i = 0; i &lt; N; i++) {\n\t\t\tlab.map[i] = Arrays.stream(br.readLine().split(&quot; &quot;)).mapToInt(Integer::parseInt).toArray();\n\t\t\tSystem.arraycopy(lab.map[i], 0, lab.copyMap[i], 0, lab.map[i].length);\n\t\t}\n\t}\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>2차원 배열에 대해 복사한다.</li>\n</ul>\n<h2>📕 참고</h2>\n<ul>\n<li><a href=\"https://coding-factory.tistory.com/548\">[Java] 자바 배열을 복사하는 다양한 방법 (깊은복사, 얕은복사)</a></li>\n</ul>","frontmatter":{"title":"📃 얕은 복사와 깊은 복사","date":"March 19, 2022","update":"March 19, 2022","tags":["Java"],"series":"📃 Java 지식"},"fields":{"slug":"/[Java지식]얕은복사&깊은복사/","readingTime":{"minutes":7.065}}},"seriesList":{"edges":[{"node":{"id":"92c9220c-c4b0-59a2-a626-5a22f979bf39","fields":{"slug":"/[Java지식]얕은복사&깊은복사/"},"frontmatter":{"title":"📃 얕은 복사와 깊은 복사"}}},{"node":{"id":"ccb919b8-dc72-524a-8a71-a85c4554249f","fields":{"slug":"/[Java지식]HashMap&LinkedHashMap/"},"frontmatter":{"title":"📃 HashMap과 LinkedHashMap"}}},{"node":{"id":"b411da00-d32a-54d0-8c93-b036f2e17a1b","fields":{"slug":"/[Java지식]정규표현식/"},"frontmatter":{"title":"📃 정규표현식"}}},{"node":{"id":"da3b5248-1d87-5d2e-8059-8d48fba73571","fields":{"slug":"/[CS]HashMap동작방식/"},"frontmatter":{"title":"📂 HashMap 동작방식"}}},{"node":{"id":"edb0af29-81ae-56b7-8e15-2784d3516f14","fields":{"slug":"/[Java지식]직렬화&역직렬화/"},"frontmatter":{"title":"📃 직렬화(Serialization)와 역직렬화(Deserialization)"}}},{"node":{"id":"9d8d34a8-1425-57bb-8ac9-d44ca2ff2b9d","fields":{"slug":"/[Java지식]Doit!1.자바시작하기/"},"frontmatter":{"title":"📃 [Do it!] 1. 자바 시작하기"}}},{"node":{"id":"50e3354d-f13b-5ec2-a23f-ee69f04e6024","fields":{"slug":"/[Java지식]Doit!2.자료형/"},"frontmatter":{"title":"📃 [Do it!] 2. 자료형"}}},{"node":{"id":"f8cd4081-f87d-5356-9b19-7dc226f4d02f","fields":{"slug":"/[Java지식]Doit!3.연산자/"},"frontmatter":{"title":"📃 [Do it!] 3. 연산자"}}},{"node":{"id":"b77bd607-9b4c-5019-98ba-d0d9b163657e","fields":{"slug":"/[Java지식]forLoop/"},"frontmatter":{"title":"📃 for loop vs. enhanced for loop"}}}]},"previous":{"fields":{"slug":"/[BOJ]14502/"},"frontmatter":{"title":"👩‍💻 14502. 연구소"}},"next":{"fields":{"slug":"/[BOJ]17779/"},"frontmatter":{"title":"👩‍💻 17779. 게리맨더링 2"}}},"pageContext":{"id":"92c9220c-c4b0-59a2-a626-5a22f979bf39","series":"📃 Java 지식","previousPostId":"099b2576-7d05-5872-a9f0-f1ee6efd3a9a","nextPostId":"50eef059-4e55-5f14-a9cf-fb01b6506f02"}},"staticQueryHashes":[]}